package com.nondo.rdp.finance.endpoint.api.app.search;

import com.nondo.rdp.auth.endpoint.model.ConvertCall;
import com.nondo.rdp.auth.endpoint.model.Page;
import com.nondo.rdp.auth.endpoint.model.Query;
import com.nondo.rdp.core.common.BeanUtils;
import com.nondo.rdp.core.common.CommUtil;
import com.nondo.rdp.core.model.View;
import com.nondo.rdp.finance.domain.analysis.Analysis;
import com.nondo.rdp.finance.model.analysis.AnalysisBean;
import com.nondo.rdp.finance.service.analysis.AnalysisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@RestController("apiAppSearch")
@RequestMapping("/api/app/search")
public class SearchEndpoint {
    @Autowired
    AnalysisService analysisService;

    @RequestMapping("/analysis")
    public View<Page<AnalysisBean>> list(HttpServletRequest request, HttpServletResponse response, @RequestBody Query<Analysis> query) {
        View<Page<AnalysisBean>> view = new View(20000, "获取数据成功");

        Analysis analysis = query.getData();

        Page<Analysis> page = analysisService.findAll(new Page<Analysis>(query.getPage(), query.getSize()), analysis);

        Page<AnalysisBean> resultPage = page.convertPage(new ConvertCall<Analysis, Page<AnalysisBean>>() {
            @Override
            public Page<AnalysisBean> execute(Page<Analysis> srcPage) {
                Page<AnalysisBean> analysisBeanPage = new Page<AnalysisBean>(srcPage.getPageNumber(), srcPage.getPageSize(), srcPage.getTotalPages(), srcPage.getTotalElements());
                //处理数据
                List<AnalysisBean> list = new ArrayList<AnalysisBean>();
                for (Object item : srcPage.getContent()) {
                    AnalysisBean analysisBean = new AnalysisBean();
                    BeanUtils.copy(item, analysisBean);
                    //处理返回日期
                    analysisBean.setCreatedDateString(CommUtil.dateFormat(analysisBean.getCreateDate(), "MM.dd"));

                    analysisBean.setMainImg(CommUtil.getFileUrl(analysisBean.getMainImg()));
                    list.add(analysisBean);
                }
                analysisBeanPage.setContent(list);

                return analysisBeanPage;
            }
        });

        view.setData(resultPage);

        return view;
    }
}